const { pool } = require('./config/db');

// 移除订单地址表的外键约束
async function removeForeignKeyConstraint() {
  try {
    console.log('开始移除外键约束...');
    
    // 先查询现有的外键约束名称
    const showKeysQuery = `
      SELECT CONSTRAINT_NAME 
      FROM information_schema.KEY_COLUMN_USAGE 
      WHERE TABLE_SCHEMA = 'aizaijia' 
      AND TABLE_NAME = 'order_addresses' 
      AND REFERENCED_TABLE_NAME = 'orders';
    `;
    
    const [keysResult] = await pool.execute(showKeysQuery);
    
    if (keysResult.length > 0) {
      const constraintName = keysResult[0].CONSTRAINT_NAME;
      console.log(`找到外键约束: ${constraintName}`);
      
      // 移除外键约束
      const dropConstraintQuery = `
        ALTER TABLE order_addresses 
        DROP FOREIGN KEY ${constraintName};
      `;
      
      await pool.execute(dropConstraintQuery);
      console.log('外键约束移除成功!');
    } else {
      console.log('未找到外键约束，可能已经被移除');
    }
    
    console.log('操作完成!');
  } catch (error) {
    console.error('移除外键约束失败:', error);
  } finally {
    // 关闭数据库连接
    pool.end();
  }
}

// 运行脚本
removeForeignKeyConstraint();